package org.e_gold.safe.acc.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.e_gold.model.UserAccount;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public abstract class TSATransferAbstract extends TSAAuthorizeAbstract {

	private static final Logger log = Logger.getLogger(TSATransferAbstract.class);

	private static final String TXT_AMOUNT = "ctl00$main$TransferFunds$txtAmount";
	private static final String TXT_PASSWORD = "ctl00$main$TransferFunds$txtPassword";

	protected void transfer(float amount, Document transferPage, UserAccount user) {

		log.info(":: Start transfer amount : " + amount);
		Map<String, String> formData = prepareTransferFormData(amount, transferPage, user.getPassword());
		if (MapUtils.isNotEmpty(formData)) {
			// get form POST action URL
			if (transferPage.getElementById("aspnetForm") != null) {
				String formAction = transferPage.getElementById("aspnetForm").attr("action");
				if (StringUtils.isNotEmpty(formAction)) {
					String postURL = BANK_TRANSFER_URL + formAction;
					log.info(":: POST BANK TRANSFER FORM DATA");
					for (Entry<String, String> e : formData.entrySet()) {
						log.info("" + e.getKey() + ":" + e.getValue());
					}
					postForm(postURL, formData, ipad);
				}
			}
		}
	}

	private Map<String, String> prepareTransferFormData(float amount, Document transferPage, String password) {

		if (transferPage != null && amount >= 0.1f && StringUtils.isNotEmpty(password)) {
			Elements els = transferPage.select("input");
			if (CollectionUtils.isNotEmpty(els)) {
				Map<String, String> formData = new HashMap<String, String>();
				for (Element e : els) {
					if (e != null && StringUtils.isNotEmpty(e.attr("name"))) {
						String name = e.attr("name");
						formData.put(name, e.attr("value"));
						if (TXT_AMOUNT.equalsIgnoreCase(name))
							formData.put(name, amount + "");
						if (TXT_PASSWORD.equalsIgnoreCase(name))
							formData.put(name, password);
					}
				}
				formData.put("__EVENTTARGET", "ctl00$main$TransferFunds$lkSbmtTransferFunds");
				formData.put("bet365ss", "1920 x 1080");
				formData.put("ctl00$main$TransferFunds$cbTrnFrm", "1");
				formData.put("ctl00$main$TransferFunds$cbTrnTo", "4");
				return formData;
			}
		}
		return null;
	}
}
